package com.heima.search.service.impl;

import com.heima.common.threadlocal.UserThreadLocalUtils;
import com.heima.model.search.dtos.UserSearchHistoryParamDTO;
import com.heima.search.service.SearchHistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author Fuqiang
 * @since :2023-03-31
 */
@Service
public class SearchHistoryServiceImpl implements SearchHistoryService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    public static final String KEY_PREFIX = "heima:leadnews:search";

    /**
     * 异步存储搜索关键字到redis中
     *
     * @param equipmentId 设备id
     * @param searchWord  搜索关键词
     * @param userId      app用户id
     */
    @Override
    @Async("taskExecutor")
    public void asyncSaveHistory(String equipmentId, String searchWord, Integer userId) {
        // TODO 只保留10条历史记录
        // TODO 如何实现手机端分页
        redisTemplate.boundZSetOps(this.buildKey(equipmentId, userId)).incrementScore(searchWord, 1);


    }

    /**
     * 加载用户搜索历史记录
     *
     * @param dto
     * @return
     */
    @Override
    public List<String> loadHistory(UserSearchHistoryParamDTO dto) {
        Integer userId = UserThreadLocalUtils.getUserIdAndCheckLogin();
        Set<String> valueSet = redisTemplate
                .boundZSetOps(buildKey(dto.getEquipmentId(), userId))
                .reverseRangeByScore(0, Double.MAX_VALUE);
        if (CollectionUtils.isEmpty(valueSet)) {
            return new ArrayList<>();
        }
        return new ArrayList<>(valueSet);
    }

    /**
     * 构建Redis Zset的key
     *
     * @param equipmentId
     * @param userId
     * @return
     */
    private String buildKey(String equipmentId, Integer userId) {
        return KEY_PREFIX + equipmentId;
    }
}
